package com.elvt.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.elvt.server.pojo.Employee;
import com.elvt.server.pojo.MailConstants;
import com.elvt.server.pojo.MailLog;
import com.elvt.server.service.IEmployeeService;
import com.elvt.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 作者： elvt
 * @Data 时间：2022/6/1
 * @packageName 包路径： ybg_back_end
 * @Desciption 说明： 邮件发送定时任务
 */
@Component
public class MailTask {
    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 邮件发送定时任务 每十秒发送一次
     */
    @Scheduled(cron ="0/1000 * * * * ?" )
    public void mailTask(){
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>().eq("status", 0).lt("tryTime", LocalDateTime.now()));
        //循环发送
        list.forEach(mailLog -> {
            //如果重试次数超过三次，更新状态则投递失败，不再重试
            if (3<=mailLog.getCount()){
                mailLogService.update(new UpdateWrapper<MailLog>().set("status",2).eq("msgId",mailLog.getMsgId()));

            }
            mailLogService.update(new UpdateWrapper<MailLog>().set("count",mailLog.getCount()+1).set("updateTime",LocalDateTime.now()).set("tryTime",LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT)).eq("msgId",mailLog.getMsgId()));
            //重新获取员工信息
           Employee employees = employeeService.getAllEmployeeORGgetById(mailLog.getEid()).get(0);
           //重新发送消息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTNG_KEY_NAME,employees,new CorrelationData(mailLog.getMsgId()));


        });
    }
}
